<template>
    <div class="app-container">
      <el-form label-width="120px" :model="students" :rules="formRules" ref="dataForm">
        <el-form-item label="学生名称" prop="name">
          <el-input v-model="students.name"/>
        </el-form-item>
        <el-form-item label="年级">
          <el-input-number v-model="students.grade" placeholder="请输入年级" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="出生日期">
            <el-date-picker
                v-model="students.birthDate"
                type="datetime"
                format="yyyy-MM-dd"
                placeholder="选择日期">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="学生性别">
            <el-select v-model="students.gender" clearable placeholder="请选择">
            <el-option :value=0 label="女"/>
            <el-option :value=1 label="男"/>
            </el-select>
        </el-form-item>

        <el-form-item label="班级">
            <el-cascader
                v-model="students.classId"
                :options="classOptions"
                :props="{ expandTrigger: 'hover' }"
                @change="handleChange"></el-cascader>
        </el-form-item>

        <el-form-item label="家庭地址">
          <el-input
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 5}"
              placeholder="请输入家庭地址"
              v-model="students.address">
          </el-input>
        </el-form-item>

        <el-form-item label="电话号" prop="phone">
          <el-input
              v-model="students.phone">
          </el-input>
        </el-form-item>

        <el-form-item label="身份证号" prop="idCard">
          <el-input
              v-model="students.idCard">
          </el-input>
        </el-form-item>


        <el-form-item>
          <el-button
            :disabled="saveBtnDisabled"
            type="primary"
            @click="saveOrUpdate">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
</template>
  <script>
  import students from '@/api/cms/students'
  import classes from '@/api/cms/classes'  
  export default {
    data() {
      return {
        // 存放学生信息
        students: {
            name: '',
            grade: undefined,
            birthDate: '',
            grade: undefined,
            classId: '',
            address: '',
            phone: '',
            idCard:''
        },
        saveBtnDisabled: false, // 保存按钮是否禁用
        options: undefined,
        formRules: {
            name: [
                { required: true, message: '请输入姓名', trigger: 'blur' }
            ],
            phone: [
              { pattern: /^1[3456789]\d{9}$/, message: '电话号格式不正确', trigger: 'blur' }
            ],
            idCard: [
              { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号格式不正确', trigger: 'blur' }
            ]
            
        },
        classOptions: undefined
      }
    },
    watch: {
      $route(to, from) { // 监听路由变化方式
        this.init()
      }
    },
    created() {
      // 初始化方法
      this.init();
    },
    methods: {
      init() {
        // 判断是否有id
        if (this.$route.params && this.$route.params.id) {
          const id = this.$route.params.id
          this.getInfo(id)
        } else {
            // 做添加 清空表单
            this.students =  {
              name: '',
              grade: undefined,
              birthDate: '',
              grade: undefined,
              classId: '',
              address: '',
              phone: '',
              idCard:''
            }
        }

        classes.getCascaderClass().then(res=>{
            console.log(res)
            this.classOptions = res.data.content
        }).catch(err=>{
            console.log(err)
        })
      },
      // 根据id查询方法
      getInfo(id) {
        console.log("********")
        students.getInfoById(id)
          .then(response => {
            console.log(response);
            this.students = response.data.item
          })
      },
      saveOrUpdate() {
        this.$refs.dataForm.validate(valid => {
            // console.log(valid)
            if (valid) {
            // 表单验证通过，执行提交操作
            this.saveBtnDisabled = true
            // 判断saveBtnDisabled是否有id 修改或添加
                if (!this.students.id) {
                // 添加
                this.saveData()
                } else {
                this.updateData()
                }
            } else {
            // 表单验证失败，输出错误信息
            // console.log('不通过')
                this.$message.error('请正确输入表单');
            }
        })
      },
      // 修改教师方法
      updateData() {
        students.updateInfo(this.students)
          .then(response => {
            this.$message({
              type: 'success',
              message: '修改成功!'
            })
            this.$router.push({ path: '/students/table' })
          }).catch(response => {
            this.$message({
              type: 'error',
              message: '修改失败'
            })
          })
      },
      // 保存
      saveData() {
        students.addInfo(this.students)
          .then(response => { // 添加成功
            this.$message({
              type: 'success',
              message: '保存成功!'
            })
            // 路由跳转
            this.$router.push({ path: '/students/table' })
          }).catch(response => {
            this.$message({
              type: 'error',
              message: '保存失败'
            })
          })
      },
      handleChange(value) {      
        this.students.classId = value[1];
        console.log(this.students.classId);
      }
    }
  }
  </script>
  